import uvicorn
from compute_node_nf import ComputeNode, app
from config.base_config import TOPO_CONFIG_FILE
from protocol import NodeInfo
import sys
import json

import logging
# Configure logging
logging.basicConfig(level=logging.INFO,  # Set desired logging level
                    filename="logs/app.log",
                    format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def main():
    node_id = sys.argv[1]
    node_type = sys.argv[2]
    host = "0.0.0.0"
    real_host = ""
    port =""
    compute_capacity = ""

    # 示例邻居节点配置（实际使用时应该通过配置文件加载）
    try:
        with open(TOPO_CONFIG_FILE, "r") as f:
            topo_config = json.load(f)
    except FileNotFoundError:
        logger.error(f"Config file {TOPO_CONFIG_FILE} not found.")
        sys.exit(1)  # Exit if the config file is missing
    except json.JSONDecodeError:
        logger.error(f"Config file {TOPO_CONFIG_FILE} is not valid JSON.")
        sys.exit(1)  # Exit if the config file is corrupted


    neighbors = {}
    for apps in topo_config["applications"]:
        if apps["name"] == node_id:
            real_host = apps["ip"]
            port = apps["port"]
            compute_capacity = apps["capacity"] / 1000

    logger.info(f"Node Configuration: host={host}, port={port}, compute_capacity={compute_capacity}")  # Log the configuration
    logger.info(f"Neighbors: {neighbors}")


    # 创建计算节点
    try:
        node = ComputeNode(
            node_id=node_id,
            node_type=node_type,
            host=host,
            real_host=real_host,
            port=port,
            compute_capacity=compute_capacity,
            memory_capacity=16.0,
        )
    except Exception as e:
        logger.error(f"Error creating ComputeNode: {e}")
        sys.exit(1) # Exit on failure


    # 设置 FastAPI 应用的状态
    app.state.node = node

    # 启动 FastAPI 服务器
    logger.info(f"计算节点 {node_id} 已启动在 {host}:{port}")
    try:
        uvicorn.run(app, host=host, port=int(port)) # ensure port is an integer
    except Exception as e:
        logger.error(f"Error starting Uvicorn: {e}")
        sys.exit(1) # Exit if uvicorn fails to start

if __name__ == "__main__":
    # python start_node.py co1 COMPUTE
    # python start_node.py co2 COMPUTE 127.0.0.1 5212
    # docker run -d --name co1 -p 5211:5211 -v $(pwd)/config:/app/config task-node co1 COMPUTE
    # docker run -d --name co2 -p 5212:5212 -v $(pwd)/config:/app/config task-node co2 COMPUTE
    main()